package com.hw.controller;

import com.github.pagehelper.PageInfo;
import com.hw.dto.R;
import com.hw.pojo.Users;
import com.hw.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @ClassName: UserController
 * @Description: 用户controller
 * @Author: vie0134
 * @Date: 2020-12-14 19:37
 * @Version: 1.0
 **/
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/findAllUser")
    public R findAllUser(@RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "10") int limit,
                         String username, String status) {
        PageInfo<Users> pageInfo = userService.findAllUser(page, limit, username, status);
        return R.setSuccess(pageInfo);
    }

    @RequestMapping("/user/{id}")
    public R findUserById(@PathVariable Integer id) {
        Users user = userService.findUserById(id);
        return R.setSuccess(user);
    }

    @RequestMapping("/login")
    public R login(String username, String password, HttpServletRequest request) {
        Users user = userService.login(username, password);
        request.getSession().setAttribute("user", user);
        return R.setSuccess(null);
    }

    @PutMapping("/user")
    public R addUser(@RequestBody Users users) {
        userService.addUser(users);
        return R.setSuccess(null);
    }

    @PostMapping("/user")
    public R updateUser(@RequestBody Users users) {
        userService.updateUser(users);
        return R.setSuccess(null);
    }

    @RequestMapping("/deleteUserById")
    public R deleteUserById(Integer id) {
        userService.deleteUserById(id);
        return R.setSuccess(null);
    }

    @DeleteMapping("/user")
    public R deleteUserByIds(String[] ids) {
        userService.deleteUserByIds(Arrays.asList(ids));
        return R.setSuccess(null);
    }
}
